<template>
  <div class="scene-config">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">🎬 场景配置</h2>
      <p class="page-subtitle">管理和编辑4个场景图片</p>
    </div>

    <!-- 场景图片网格 -->
    <div class="scenes-container">
      <div class="scenes-grid">
        <div 
          v-for="(scene, index) in scenes" 
          :key="scene.id" 
          class="scene-item">
          
          <!-- 场景标题 -->
          <div class="scene-header">
            <h3 class="scene-title">{{ scene.sceneName }}</h3>
            <div class="scene-type-badge">{{ scene.sceneType }}</div>
            <div class="scene-actions">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="editScene(index)"
                :disabled="scene.isDefault && !scene.sceneImage">
                编辑
              </el-button>
            </div>
          </div>

          <!-- 图片显示区域 -->
          <div class="scene-image-area">
            <div class="image-container" @click="editScene(index)">
              <img
                v-if="scene.sceneImage"
                :src="scene.sceneImage | imageUrl"
                :alt="scene.sceneName"
                class="scene-image">
              <div v-else class="no-image-placeholder">
                <i class="el-icon-picture-outline"></i>
                <p>点击上传{{ scene.sceneName }}</p>
              </div>
            </div>
          </div>

          <!-- 场景信息 -->
          <div class="scene-info">
            <div class="scene-status">
              <span v-if="scene.isDefault" class="default-badge">默认场景</span>
              <span v-else class="custom-badge">自定义</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="`编辑 ${currentScene.sceneName}`"
      :visible.sync="editDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      class="edit-dialog">
      
      <div class="edit-content">
        <!-- 当前图片预览 -->
        <div class="current-image-preview">
          <h4>当前图片</h4>
          <div class="preview-container">
            <img
              v-if="currentScene.sceneImage"
              :src="currentScene.sceneImage | imageUrl"
              :alt="currentScene.sceneName"
              class="preview-image">
            <div v-else class="no-preview">
              <i class="el-icon-picture-outline"></i>
              <p>暂无图片</p>
            </div>
          </div>
        </div>

        <!-- 图片上传区域 -->
        <div class="upload-section">
          <h4>上传新图片</h4>
          <div class="upload-area">
            <div 
              class="upload-zone" 
              @click="selectImage"
              :class="{ 'has-image': newImagePreview }">
              <img 
                v-if="newImagePreview" 
                :src="newImagePreview" 
                alt="新图片预览"
                class="new-image-preview">
              <div v-else class="upload-placeholder">
                <i class="el-icon-upload"></i>
                <p>点击选择图片</p>
                <p class="upload-tips">支持 JPG、PNG、GIF 格式，最大 5MB</p>
              </div>
            </div>
            <input 
              ref="fileInput" 
              type="file" 
              accept="image/*" 
              @change="handleImageUpload" 
              style="display: none;">
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取消</el-button>
        <el-button
          v-if="currentScene.sceneImage"
          type="danger"
          @click="removeImage">
          删除图片
        </el-button>
        <el-button
          type="primary"
          @click="saveScene"
          :disabled="!newImagePreview && !currentScene.sceneImage">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SceneService from '@/api/sceneService'

export default {
  name: 'SceneConfig',
  data() {
    return {
      // 场景配置列表
      scenes: [],

      // 编辑状态
      editDialogVisible: false,
      currentSceneIndex: 0,
      currentScene: {},
      newImagePreview: null,
      newImageData: null,
      newImageFile: null  // 存储原始文件对象
    }
  },

  mounted() {
    this.loadScenes()
  },

  methods: {
    // 加载场景数据
    async loadScenes() {
      try {
        const result = await SceneService.getSceneTemplates()

        if (result.success) {
          this.scenes = result.data || []

          // 如果API返回的场景少于4个，用模拟数据补充
          if (this.scenes.length < 4) {
            const mockData = SceneService.generateMockData()
            const transformedMockData = this.$transformArrayImageUrls(mockData, ['sceneImage'])

            // 合并真实数据和模拟数据，确保有4个场景
            const existingIds = this.scenes.map(s => s.id)
            const additionalScenes = transformedMockData.filter(s => !existingIds.includes(s.id))

            this.scenes = [...this.scenes, ...additionalScenes].slice(0, 4)
          }
        } else {
          this.$message.error(result.message || '加载场景数据失败')
          // 使用模拟数据作为备用
          this.scenes = this.$transformArrayImageUrls(
            SceneService.generateMockData(),
            ['sceneImage']
          )
        }

      } catch (error) {
        this.$message.error('加载场景数据失败：' + error.message)
        // 使用模拟数据作为备用
        this.scenes = this.$transformArrayImageUrls(
          SceneService.generateMockData(),
          ['sceneImage']
        )
      }
    },

    // 编辑场景
    editScene(index) {
      this.currentSceneIndex = index
      this.currentScene = { ...this.scenes[index] }
      this.newImagePreview = null
      this.newImageData = null
      this.newImageFile = null
      this.editDialogVisible = true
    },

    // 选择图片
    selectImage() {
      this.$refs.fileInput.click()
    },

    // 处理图片上传
    async handleImageUpload(event) {
      const file = event.target.files[0]
      if (!file) return

      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        this.$message.error('只能上传图片文件')
        return
      }

      // 验证文件大小 (5MB)
      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('图片大小不能超过5MB')
        return
      }

      try {
        // 保存原始文件对象
        this.newImageFile = file

        // 转换为Base64用于预览
        const base64 = await this.fileToBase64(file)
        this.newImagePreview = base64
        this.newImageData = base64

        this.$message.success('图片选择成功')
      } catch (error) {
        this.$message.error('图片处理失败：' + error.message)
      }
    },

    // 保存场景
    async saveScene() {
      try {
        // 检查是否有新图片文件
        if (!this.newImageFile) {
          this.$message.warning('请选择要上传的图片文件')
          return
        }

        // 获取场景类型
        const sceneType = this.currentScene.sceneType
        if (!sceneType) {
          this.$message.error('场景类型不能为空')
          return
        }

        // 调用新的编辑默认场景接口
        const result = await SceneService.editDefaultTemplate(this.newImageFile, sceneType)

        if (result.success) {
          // 更新本地数据
          this.currentScene.sceneImage = (result.data && result.data.sceneImage) || this.newImageData
          this.scenes.splice(this.currentSceneIndex, 1, { ...this.currentScene })
          this.$message.success('场景保存成功')
          this.editDialogVisible = false

          // 重新加载场景数据
          await this.loadScenes()
        } else {
          this.$message.error(result.message || '保存失败')
        }

      } catch (error) {
        this.$message.error('保存失败：' + error.message)
      }
    },

    // 删除图片
    async removeImage() {
      this.$confirm('确定要删除这张图片吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 调用API删除图片
          const result = await SceneService.updateSceneTemplate(this.currentScene.id, {
            sceneImage: null
          })

          if (result.success) {
            this.currentScene.sceneImage = null
            this.scenes.splice(this.currentSceneIndex, 1, { ...this.currentScene })

            this.$message.success('图片删除成功')
            this.editDialogVisible = false
          } else {
            this.$message.error(result.message || '删除失败')
          }

        } catch (error) {
          this.$message.error('删除失败：' + error.message)
        }
      })
    },

    // 取消编辑
    cancelEdit() {
      this.editDialogVisible = false
      this.newImagePreview = null
      this.newImageData = null
      this.newImageFile = null
    },

    // 文件转Base64
    fileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = () => resolve(reader.result)
        reader.onerror = reject
        reader.readAsDataURL(file)
      })
    }
  }
}
</script>

<style scoped>
.scene-config {
  padding: 24px;
  background: #f8fafc;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 32px 20px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
}

.page-subtitle {
  margin: 0;
  font-size: 16px;
  color: #6b7280;
}

/* 场景容器 */
.scenes-container {
  max-width: 1200px;
  margin: 0 auto;
}

.scenes-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

/* 场景项目 */
.scene-item {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.scene-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
}

/* 场景头部 */
.scene-header {
  padding: 20px 24px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f1f5f9;
  flex-wrap: wrap;
  gap: 12px;
}

.scene-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  flex: 1;
}

.scene-type-badge {
  background: #e0f2fe;
  color: #0369a1;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.scene-actions {
  display: flex;
  gap: 8px;
}

/* 图片区域 */
.scene-image-area {
  padding: 24px;
}

.image-container {
  width: 100%;
  height: 200px; /* Fixed height for better control, adjust as needed */
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid #e2e8f0;
  display: flex; /* Use flexbox for centering */
  align-items: center; /* Center vertically */
  justify-content: center; /* Center horizontally */
  background-color: #f0f2f5; /* Background for empty space if image doesn't fill */
}

.image-container:hover {
  border-color: #3b82f6;
  transform: scale(1.02);
}

.scene-image {
  max-width: 100%; /* Ensure image doesn't overflow */
  max-height: 100%; /* Ensure image doesn't overflow */
  object-fit: contain; /* Show complete content, maintain aspect ratio */
  display: block; /* Remove extra space below image */
}

.no-image-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8fafc;
  color: #64748b;
  transition: all 0.3s ease;
}

.no-image-placeholder:hover {
  background: #f1f5f9;
  color: #3b82f6;
}

.no-image-placeholder i {
  font-size: 32px;
  margin-bottom: 8px;
}

.no-image-placeholder p {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

/* 场景信息 */
.scene-info {
  padding: 16px 24px 24px;
}

.scene-status {
  display: flex;
  justify-content: center;
}

.default-badge {
  background: #dcfce7;
  color: #166534;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.custom-badge {
  background: #fef3c7;
  color: #92400e;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

/* 编辑对话框 */
.edit-dialog .edit-content {
  padding: 8px 0;
}

.current-image-preview,
.upload-section {
  margin-bottom: 24px;
}

.current-image-preview h4,
.upload-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

/* 当前图片预览 */
.preview-container {
  width: 100%;
  height: 160px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-preview {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f9fafb;
  color: #9ca3af;
}

.no-preview i {
  font-size: 24px;
  margin-bottom: 8px;
}

.no-preview p {
  margin: 0;
  font-size: 14px;
}

/* 上传区域 */
.upload-area {
  width: 100%;
}

.upload-zone {
  width: 100%;
  height: 160px;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.upload-zone:hover {
  border-color: #3b82f6;
  background: #f8faff;
}

.upload-zone.has-image {
  border-style: solid;
  border-color: #10b981;
}

.new-image-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  text-align: center;
  color: #6b7280;
}

.upload-placeholder i {
  font-size: 32px;
  margin-bottom: 12px;
  color: #9ca3af;
}

.upload-placeholder p {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 500;
}

.upload-tips {
  font-size: 12px !important;
  color: #9ca3af !important;
  font-weight: 400 !important;
}

/* 对话框底部 */
.dialog-footer {
  text-align: right;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .scenes-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
  }
}

@media (max-width: 900px) {
  .scenes-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .scene-config {
    padding: 16px;
  }

  .page-header {
    padding: 24px 16px;
    margin-bottom: 24px;
  }

  .page-title {
    font-size: 24px;
  }

  .page-subtitle {
    font-size: 14px;
  }

  .scenes-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .scene-header {
    padding: 16px 20px 12px;
  }

  .scene-title {
    font-size: 16px;
  }

  .scene-image-area {
    padding: 20px;
  }

  .image-container {
    padding-bottom: 177.78%; /* 保持手机比例 */
  }

  .scene-description {
    padding: 12px 20px 20px;
  }
}

@media (max-width: 480px) {
  .scene-config {
    padding: 12px;
  }

  .page-header {
    padding: 20px 12px;
  }

  .scenes-grid {
    gap: 12px;
  }

  .scene-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .scene-actions {
    width: 100%;
    justify-content: center;
  }
}
</style>
